package com.kinon.norogamilk.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.kinon.norogamilk.R;
import com.kinon.norogamilk.bean.ComBean;
import com.kinon.norogamilk.bean.TakeBean;
import com.kinon.norogamilk.http.CommonSubscriber;
import com.kinon.norogamilk.http.MilkApi;
import com.kinon.norogamilk.http.StrCallback;
import com.kinon.norogamilk.ui.base.BaseActivity;
import com.kinon.norogamilk.util.RxBus;
import com.kinon.norogamilk.util.RxUtil;

import java.util.ArrayList;
import java.util.Arrays;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by lhqq on 2017-12-18.
 * 支付成功出货处理
 */

public class PaySuccessActivity extends BaseActivity implements View.OnClickListener {

    protected CompositeDisposable mCompositeDisposable;
    private ImageView img_textspec;
    private ImageView img_step;
    private ImageView img_heatProcess;
    private Button btn_back;
    private TextView tv_payhint;
    //    private SerialControl mSerCon;
    private String orderid;
    private boolean mIsHeat;
    private int mPset = 0;
    private TakeBean takeData;
    private int dataPosition = 0;
    private int goodCount = 0;
    private int indexNum = 0;
    private int totalNum = 0;
    private boolean isStopThread = false;
    private MySendThread mSendThread;
    private int mSign = 0;
    private ArrayList<String> raodList;
    private Handler myHandler = new Handler();
    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
//            totalNum=indexNum-1;
            if (totalNum >= 0) {
                Log.e(TAG, "发送出货===============");
                indexNum--;
                sendPortData(sendString(raodList.get(totalNum)));

            }
        }
    };
    private Runnable backRunnable = new Runnable() {
        @Override
        public void run() {

            intent(0);
        }
    };
    private byte highByt = 1;
    private int updateOrderError = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_paysuccess_layout);
        initView();
    }

    private void initView() {
        img_textspec = findViewById(R.id.img_textspec);
        img_step = findViewById(R.id.img_step);
        img_heatProcess = findViewById(R.id.img_heatProcess);
        btn_back = findViewById(R.id.btn_back);
        tv_payhint = findViewById(R.id.tv_payhint);
        btn_back.setVisibility(View.VISIBLE);
        btn_back.setOnClickListener(this);
//        mSerCon=new SerialControl();

        OpenComPort(mSerCon);


        orderid = getIntent().getStringExtra("orderid");
        mIsHeat = getIntent().getBooleanExtra("isHeat", false);
        String strTakeData = getIntent().getStringExtra("strTakeData");

        if (!TextUtils.isEmpty(strTakeData)) {
//            Log.e(TAG, "strTakeData!=null ");
            takeData = (new Gson()).fromJson(strTakeData, TakeBean.class);
            orderid = takeData.getOrderid();
            Log.e(TAG, "orderid==== " + orderid);
            indexNum = takeData.getTotal_num();
            totalNum = takeData.getTotal_num() - 1;

//            totalNum=takeData.getTotal_num();
//            sendPortData("4546CB07003b000077B6");
            //查询主板状态
//            sendPortData(sendString(0x02));


            addList();
//            sendOutGoods();
            myHandler.postDelayed(mRunnable, 300);
        }
//        dataReceived();
        newDataReceived();
    }

    private void addList() {
        raodList = new ArrayList<>();
        for (int i = 0; i < takeData.getPickup().size(); i++) {
            for (int y = 0; y < takeData.getPickup().get(i).getGoods_count(); y++) {
                raodList.add(takeData.getPickup().get(i).getGoods_name());
            }
        }
    }

    private void sendOutGoods() {
        sendPortData(sendString(raodList.get(totalNum)));
    }

    //    protected void sendPortData(String sOut){
//        if (mSerCon!=null ){
//            mSerCon.sendHex(sOut);
//        }
//    }
//     private int i=0;
    private void newDataReceived() {
        mCompositeDisposable = new CompositeDisposable();
        Disposable dis = RxBus.getDefault().toFlowable(ComBean.class)
                .subscribeOn(AndroidSchedulers.mainThread())
                .compose(RxUtil.<ComBean>rxSchedulerHelper())
                .subscribeWith(new CommonSubscriber<ComBean>() {
                    @Override
                    public void onFail(Throwable t, int code, String msg) {
                    }

                    @Override
                    public void onNext(final ComBean comBean) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Thread.sleep(500);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }

//                                Log.e(TAG, "Main =="+MyFunc.ByteArrToHex(comBean.getbRec()));
                                if (comBean.getbRec().length > 6) {
//                                    Log.e(TAG, "Main =="+MyFunc.ByteArrToHex(comBean.getbRec()));
//                                    Log.e(TAG, "getbRec =="+comBean.getbRec()[5]);
                                    if (comBean.getbRec()[5] == 52) { //出货返回
                                        //查询主板状态
                                        Log.e(TAG, "主板状态查询----");
                                        sendPortData(sendString(0x02));
                                    } else if (comBean.getbRec()[5] == 54 && mSign == 6) { //交易数据返回
//                                        Log.e(TAG, "交易数据返回 =="+MyFunc.ByteArrToHex(comBean.getbRec()));
                                        //无故障
                                        if (comBean.getbRec().length > 31 &&
                                                comBean.getbRec()[28] == 0 &&
                                                comBean.getbRec()[29] == 0 &&
                                                comBean.getbRec()[30] == 0 &&
                                                comBean.getbRec()[31] == 0) {
                                            //查询主板状态
                                            Log.e(TAG, "主板状态查询==交易数据返回----");
                                            sendPortData(sendString(0x02));
//                                            totalNum--;
                                        } else {
//                                            Log.e(TAG, "Main =="+MyFunc.ByteArrToHex(comBean.getbRec()));
                                            //有故障 出货失败
                                            Log.e(TAG, "有故障 出货失败----" + Arrays.toString(comBean.getbRec()));
                                            img_textspec.setImageResource(R.drawable.img_text_shiperror);
                                            img_step.setImageResource(R.drawable.img_cow_sorry);
                                        }
                                    } else if (comBean.getbRec()[5] == 59) { //重置返回
                                        //查询主板状态
                                        Log.e(TAG, "主板状态查询==重置后----");
                                        sendPortData(sendString(0x02));

                                    } else if (comBean.getbRec()[5] == 2) { //主板状态查询返回
                                        if (comBean.getbRec().length > 12) {


                                            if (comBean.getbRec()[12] == 2 && mSign != 2) {//从0变为2正在出货
                                                mSign = 2;
                                                //查询主板状态
                                                Log.e(TAG, "主板状态查询==正在出货----");
//                                            Log.e(TAG, "主板状态查询==2 =="+MyFunc.ByteArrToHex(comBean.getbRec()));
                                                sendPortData(sendString(0x02));
                                            } else if (comBean.getbRec()[12] == 6 && mSign != 6) { //从2变为6出货完成
                                                mSign = 6;
                                                //发送数据交易指令
                                                Log.e(TAG, "发送数据交易指令==出货完成----");

//                                            Log.e(TAG, "主板状态查询==6 =="+MyFunc.ByteArrToHex(comBean.getbRec()));
//                                                sendPortData("4546CB05003600009FB5");
                                                sendPortData(sendString(0x36));

                                            } else if (comBean.getbRec()[12] == 4 && mSign != 4) { //从6变为4交易数据已上传
                                                mSign = 4;
                                                //将事件标志为0
                                                Log.e(TAG, "将事件标志置为0----");
//                                                sendPortData("4546CB07003b000077B6");
                                                sendPortData(sendString(0x3b));
                                            } else if (comBean.getbRec()[12] == 0 && mSign != 0) {
                                                mSign = 0;
                                                // 完成
                                                Log.e(TAG, "完成----");
                                                totalNum--;
                                                setout();

                                            } else { //主板轮询
                                                Log.e(TAG, "主板轮询----");
                                                sendPortData(sendString(0x02));
                                            }
                                        } else {//返回长度少于12的时候
                                            Log.e(TAG, "返回长度少于12的时候主板轮询----");
                                            sendPortData(sendString(0x02));
                                        }
                                    }
                                } else { //返回长度少于6的时候
                                    Log.e(TAG, "返回长度少于6的时候主板轮询----");
                                    sendPortData(sendString(0x02));
                                }

                            }
                        });
                    }
                });
        mCompositeDisposable.add(dis);

    }

    private void setout() {
//        if(totalNum!=indexNum-1){
//            totalNum=indexNum-1;
//        }
        Log.e(TAG, "totalNum== " + totalNum);
        if (totalNum < 0) {
//                                    btn_back.setVisibility(View.VISIBLE);
            tv_payhint.setText("出货成功,请取走您的商品");
            img_textspec.setImageResource(R.drawable.img_text_shipsuccess);
            img_step.setImageResource(R.drawable.img_cow_shipsucce);
//            if (!mIsHeat) {
//
//            } else {
//                img_textspec.setImageResource(R.drawable.img_text_hatchon);
//                img_step.setImageResource(R.drawable.img_cow_put);
//                tv_payhint.setVisibility(View.GONE);
//                img_heatProcess.setVisibility(View.VISIBLE);
//            }
            if (mCompositeDisposable != null) {
                mCompositeDisposable.dispose();
            }
            //更新订单状态
            updateOrder(orderid);

        } else {
            myHandler.postDelayed(mRunnable, 100);
        }
    }

    private void intent(int dist) {
        if (!mIsHeat || dist == 1) {
            Intent intent = new Intent(PaySuccessActivity.this,
                    MainActivity.class);
            startActivity(intent);
            finish();
        } else {
            Intent intent = new Intent(PaySuccessActivity.this,
                    HeatingActivity.class);
            startActivity(intent);
            finish();
        }


        Log.e(TAG, "intent===: ");
    }

//    private class SerialControl extends SerialHelper {
//
////		}
//        public SerialControl(){
//        }
//
//        @Override
//        protected void onDataReceived(final ComBean ComRecData)
//        {
//            //数据接收量大或接收时弹出软键盘，界面会卡顿,可能和6410的显示性能有关
//            //直接刷新显示，接收数据量大时，卡顿明显，但接收与显示同步。
//            //用线程定时刷新显示可以获得较流畅的显示效果，但是接收数据速度快于显示速度时，显示会滞后。
//            //最终效果差不多-_-，线程定时刷新稍好一些。
//
//
//        }
//    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                intent(1);
                break;
        }
    }

    private void updateOrder(final String orderid) {
        Call<String> call = MilkApi.getInstance().updateOrder(sn, orderid);
        call.enqueue(new StrCallback<String>() {
            @Override
            public void onSuccess(Response<String> response, String data) {
//              intent();

//                mToast("订单更新成功");
                btn_back.postDelayed(backRunnable, 5000);

            }

            @Override
            public void onError(int code, String error) {
                if (updateOrderError >= 3) {
                    intent(0);
                }
                updateOrderError++;
                updateOrder(orderid);
//                intent();
//                mToast(error);
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
//        SetAutoSend(false);
        isStopThread = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mCompositeDisposable != null) {
            mCompositeDisposable.dispose();
        }

        finish();
    }

    private class MySendThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (!isInterrupted()) {
                synchronized (this) {
                    while (isStopThread) {
                        try {
                            wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                }
                sendPortData(sendString(0x02));
                try {
                    Thread.sleep(103);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
